<template>
  <div class="main">
    <el-form @submit.native.prevent="addDish">
      <el-form-item label="菜名">
        <el-input v-model="state.dish_name"></el-input>
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="state.price"></el-input>
      </el-form-item>
      <el-form-item label="图片">
        <input
          type="file"
          name="image"
          @change="handleFileChange"
          class="form-control-file"
        />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="state.description"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">添加</el-button>
        <el-button @click="goback">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { addDishApi } from "@/utils/api"; // 假设你有一个API函数用于添加菜单
const router = useRouter();

const state = ref({
  dish_name: "",
  price: "",
  image_url: null, // 修改为 null
  description: "",
  restaurant_id: router.currentRoute.value.params.id,
});

const handleFileChange = (event) => {
  state.value.image_url = event.target.files[0]; // 直接保存文件对象
};

const addDish = async () => {
  const formData = new FormData();
  Object.keys(state.value).forEach((key) => {
    if (key === "image_url") {
      formData.append("image", state.value[key]);
    } else {
      formData.append(key, state.value[key]);
    }
  });

  try {
    await addDishApi(formData); // 发送 FormData 对象
    // 提示添加成功
    alert("添加成功");
    // 添加成功后返回上一页
    router.back();
  } catch (error) {
    console.error(error);
  }
};

const goback = () => {
  window.history.back();
};
</script>

<style lang="less" scoped>
.main {
  margin: 100px;
}
</style>